<template>
  <div>
    <a-button type="primary" style="margin-top: 20px" @click="showModal">
      <a-icon type="plus" />
      根据源单生成
    </a-button>

    <a-modal
      title="销售出库单生成退库申请单"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="70%"
    >
      <!-- 搜索表单---查询条件 -->
      <a-form v-bind="layout">
        <a-row>
          <!-- 公共部分 -->
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="申请日期">
              <a-range-picker
                v-model="searchForm.rangeDate"
                @change="getRangeTime"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="单据状态">
              <a-select v-model="searchForm.documentClosed" style="width: 100%">
                <a-select-option
                  v-for="item in documentClosedList"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item label="单据号">
              <a-select
                v-model="searchForm.document"
                showSearch
                style="width: 100%"
              >
                <a-select-option
                  v-for="(item, index) in OrderList"
                  :key="index"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 按钮 -->
        <a-row>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24" align="right"
            ><div style="margin-top: 10px">
              <a-button type="primary" @click="Search()">查询</a-button>
              <a-button style="margin-left: 8px" @click="Reset()"
                >重置</a-button
              >
            </div>
          </a-col>
        </a-row>
      </a-form>

      <a-divider />

      <!-- 备货通知单、销售订单等单据 -->
      <a-table
        style="margin-top: 20px"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        @change="handleTableChange"
        :row-selection="{
          selectedRowKeys: orderSelectedRowKeys,
          onChange: orderSelectChange,
          type: 'radio',
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <span slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="updateState(record, 1)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
          <a-popconfirm
            title="是否开启单据?"
            v-if="record.documentClosed == '关闭'"
            @confirm="updateState(record, 1)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
        </span>
      </a-table>

      <a-divider />
      <!-- 单据中的物品 -->
      <a-table
        style="margin-top: 10px"
        :columns="listColumns"
        :data-source="listDataSource"
        :scroll="{ x: 1500 }"
        :row-selection="{
          selectedRowKeys: listSelectedRowKeys,
          onChange: listSelectChange,
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <span slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="updateState(record, 2)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
          <a-popconfirm
            title="是否开启单据?"
            v-if="record.documentClosed == '关闭'"
            @confirm="updateState(record, 2)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
        </span>
      </a-table>

      <!-- 备货通知单物品信息 -->
    </a-modal>
  </div>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
import { otherOutCancelHttp } from "@/services/modules/tuiKuGuanLi/otherOutCancelApply";
const $http = new otherOutCancelHttp(); // 其他出库退库申请
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },
  {
    title: "单据号",
    dataIndex: "document",
    key: "document",
    align: "center",
  },
  {
    title: "订单日期",
    dataIndex: "documentDate",
    key: "documentDate",
    align: "center",
  },

  {
    title: "申请部门",
    dataIndex: "deptId_dictText",
    key: "deptId_dictText",
    align: "center",
  },

  {
    title: "库存组织",
    dataIndex: "pkCalbody_dictText",
    key: "pkCalbody_dictText",
    align: "center",
  },
  {
    title: "业务流程",
    dataIndex: "cbiztype_dictText",
    key: "cbiztype_dictText",
    align: "center",
  },

  {
    title: "客户",
    dataIndex: "clientId_dictText",
    key: "clientId_dictText",
    align: "center",
  },
  {
    title: "收发类别",
    dataIndex: "sendReceiveType_dictText",
    key: "sendReceiveType_dictText",
    align: "center",
  },
  {
    title: "库管员",
    dataIndex: "cwhsmanagerid_dictText",
    key: "cwhsmanagerid_dictText",
    align: "center",
  },

  {
    title: "备注",
    dataIndex: "remarks",
    key: "remarks",
    align: "center",
  },
  {
    title: "单据状态",
    dataIndex: "documentClosed",
    key: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];

const listColumns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },

  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
    width: "200px",
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    key: "measname",
    dataIndex: "measname",
    align: "center",
  },

  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
  },

  {
    title: "发货时间",
    key: "deliveryDate",
    dataIndex: "deliveryDate",
    align: "center",
    width: "180px",
  },

  {
    title: "是否赠品",
    key: "giveaway_dictText",
    dataIndex: "giveaway_dictText",
    align: "center",
  },
  {
    title: "单据状态",
    dataIndex: "documentClosed",
    align: "center",
    key: "documentClosed",
    scopedSlots: { customRender: "documentClosed" },
  },
];

export default {
  data() {
    return {
      savedocumentClosed: "", //保存单据状态上
      saveid: "", //保存的表头id
      documentClosedList: ["开启", "关闭"],
      visible: false,
      searchForm: {
        salesDepartment: "", // 销售部门
        document: "", //单据编号
        deptId: "", // 销售部门Id
        rangeDate: null, // 日期范围
        startTime: "", // 开始日期
        endTime: "", // 结束日期
      },
      saleDepartmentList: [], // 销售部门
      ClientList: [], // 客户列表

      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },

      columns,
      dataSource: [],
      orderSelectedRowKeys: [],

      listColumns,
      listDataSource: [],
      listSelectedRowKeys: [], // 列表选择

      pagination: {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      },
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 5, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      },

      Form: {
        requisitionNo: "", // 订单号
        applicationDept: "", // 销售部门
        applicationDeptId: "", // 销售部门Id
        clientId: "", // 客户
        client: "", // 客户名称
        goodsList: [], // 物品列表
      },
      OrderList: [], // 返回所有的销售出库单号
    };
  },
  mounted() {
    this.getSaleDepartmentList();
    this.getOrderList(); // 获取销售出库单单据号
  },
  methods: {
    //禁止选择的组件
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.documentClosed === "关闭",
        },
      };
    },
    //修改单据状态
    updateState(record, select) {
      let that = this;
      console.log(`选中了${select}表格信息`);
      console.log(`选中该记录返回的所有信息:`, record);
      //路线判断
      record.documentClosed === "开启"
        ? goState.call(that, "关闭", record)
        : goState.call(that, "开启", record);

      function goState(status, record) {
        console.log(`正在执行状态${status}功能:::::::::`);
        let data = {
          id: record.id,
          documentClosed: status,
          objectInformationId: record.objectInformationId,
        };
        //接口判断
        return select === 1
          ? this.updatePurchaseaAddorder(data, status)
          : this.updatePurchaseiItemiInformation(data, status);
      }
    },
    //接口关闭-上A
    updatePurchaseaAddorder(data, status) {
      console.log(111);
      $http.updateInOrOutStorageOrder(data).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(`${status}成功!`);
        console.log(`Success::::::${status}功能成功执行`);
        this.getArrayListByOriginDocument(); //获取采购订单列表
      });
    },
    //接口关闭-下
    updatePurchaseiItemiInformation(data) {
      let message = {
        id: this.saveid,
        documentClosed: this.savedocumentClosed,
        warehouseObjectInformationEntities: [
          {
            documentClosed: data.documentClosed,
            id: data.objectInformationId,
          },
        ],
      };
      $http.updateInOrOutStorageOrderAndGoods(message).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(`${status}成功!`);
        comHttp
          .getArrayListByOriginId(
            "?id=" + this.saveid + "&inOutCategoryIdentification=3"
          )
          .then((res) => {
            console.log("物品信息::::::", res);
            this.listDataSource = res.result.list;
          });
      });
    },
    // ----------- 查询的单据为：出库、销售出库、已经审核的单据 --------------
    getArrayListByOriginDocument(
      queryPath = "?pageNo=1&pageSize=5&inOutIdentification=2&inOutCategoryIdentification=3&auditMark=1&documentClosed=开启"
    ) {
      comHttp.getArrayListByOriginDocument(queryPath).then((res) => {
        console.log("销售出库单:::::", res);

        this.dataSource = [];
        const pagination = { ...this.pagination };
        pagination.total = res.result.total;
        pagination.pageSize = res.result.size;
        this.pagination = pagination;
        this.dataSource = res.result.records;
        for (let i = 0; i < res.result.records.length; i++) {
          this.dataSource[i].key = (res.result.current - 1) * 5 + i + 1;
        }
      });
    },

    // 部门按钮触发
    DepartmentChange(value, options) {
      this.searchForm.deptId = options.key;
    },

    // 时间段
    getRangeTime(date, dateString) {
      this.searchForm.startTime = dateString[0];
      this.searchForm.endTime = dateString[1];
    },

    // 列表选择
    listSelectChange(selectedRowKeys, selectedRows) {
      this.listSelectedRowKeys = selectedRowKeys;
      this.Form.goodsList = selectedRows;
    },

    // 表单选择
    orderSelectChange(selectedRowKeys, selectedRows) {
      this.orderSelectedRowKeys = selectedRowKeys;
      this.saveid = selectedRows[0].id; //保存id
      this.savedocumentClosed = selectedRows[0].documentClosed; //保存单据状态
      // 单选 拿到表单信息
      this.Form = selectedRows[0];
      this.Form[`goodsList`] = [];
      this.listSelectedRowKeys = []; // 重置物品

      this.getArrayListByOriginId(selectedRows[0].id);
    },

    // 通过销售订单单号ID,查询物品信息
    getArrayListByOriginId(id) {
      comHttp
        .getArrayListByOriginId("?id=" + id + "&inOutCategoryIdentification=3")
        .then((res) => {
          console.log("物品信息::::::", res);
          this.listDataSource = res.result.list;
          this.Form.goodsList = res.result.list;

          for (let i = 0; i < this.Form.goodsList.length; i++) {
            this.Form.goodsList[i].key = i + 1;
            // this.Form.goodsList[i].sourceNumber = this.Form.document;
          }
        });
    },

    // ----------- 重置 ------------------
    // 对话框取消
    handleCancel() {
      this.Reset();
      this.visible = false;
    },
    // 重置
    Reset() {
      this.saveid = "";
      this.savedocumentClosed = "";
      // 重置查询条件
      this.searchForm = {
        documentClosed: "开启", //单据状态
        rangeDate: null, // 日期范围
        document: "",
        startTime: "", // 开始日期
        endTime: "", // 结束日期
      };

      this.resetPagination(); // 重置分页情况
      this.getArrayListByOriginDocument(); // 重置销售订单
      this.listDataSource = []; // 重置物品数据
      // 重置选择框中选中的值
      this.listSelectedRowKeys = [];
      this.orderSelectedRowKeys = [];
    },

    // 重置当前页码及页码参数
    resetPagination() {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      //查询参数
      this.queryParam = {
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      };
    },

    // ----------- 查询 ------------------
    // 查询
    Search() {
      this.resetPagination(); // 重置分页情况

      let queryPath = this.getQueryPath();
      this.getArrayListByOriginDocument(queryPath);
      console.log("查询条件为:::", queryPath);
    },
    // 分页函数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;
      let queryPath = this.getQueryPath();
      this.getArrayListByOriginDocument(queryPath);
    },

    // 获取全局查询条件
    getQueryPath() {
      let queryPath =
        "?pageNo=" +
        this.queryParam.page +
        "&pageSize=5" +
        "&inOutIdentification=2&inOutCategoryIdentification=3&auditMark=1" +
        "&beginDate=" +
        this.searchForm.startTime +
        "&endDate=" +
        this.searchForm.endTime +
        "&documentClosed=" +
        this.searchForm.documentClosed +
        "&document=" +
        this.searchForm.document;
      return queryPath; // 返回的查询条件
    },

    // 打开对话框
    showModal() {
      this.getArrayListByOriginDocument();
      this.visible = true;
    },
    // 对话框提交
    handleOk() {
      console.log(this.Form);
      this.$emit("select-data", this.Form);
      this.visible = false;
      this.resetPagination(); // 重置分页
    },

    // ----------- 获取销售部门列表 --------------
    getSaleDepartmentList() {
      this.saleDepartmentList = [];
      comHttp.getSaleDepartment().then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].value,
            title: res.result[i].title,
          };
          this.saleDepartmentList.push(data);
        }
      });
    },
    // 获取单据号列表
    getOrderList() {
      let queryPath = "?string=XSCK-";
      comHttp.getOrderList(queryPath).then((res) => {
        console.log("获取销售订单列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          this.OrderList.push(res.result[i]);
        }
      });
    },
  },
};
</script>

<style>
</style>



